import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { FormattedMessage, injectIntl } from 'react-intl';
import { stripesConnect } from '@folio/stripes/core';
import get from 'lodash/get';
import { MultiColumnList } from '@folio/stripes/components';
import { StripesConnectedSource } from '@folio/stripes/smart-components';
import ExprotExcel from '../../util/ExportExcel';
import SearchForm from '../../components/party-notify-log/search-form';

class SmsDetailsStatistics extends Component {
  static manifest = Object.freeze({

    notifyLogQuery: {
      initialValue: ''
    },
    resultCount: {
      initialValue: 10
    },
    smsDetailsRecords: {
      type: 'okapi',
      path: 'party/notify_log',
      recordsRequired: '%{resultCount}',
      perRequest: 10,
      limitParam: 'limit',
      records: 'notifyLogGroup',
      GET: {
        params: {
          query: '%{notifyLogQuery}'
        }
      }
    }
  });

  static propTypes = {
    okapi: PropTypes.object,
    stripes: PropTypes.shape({
      logger: PropTypes.object
    }).isRequired,
    resources: PropTypes.object,
    mutator: PropTypes.shape({

      notifyLogQuery: PropTypes.string
    }).isRequired,
    dictionary: PropTypes.object
  };

  constructor(props) {
    super(props);
    this.logger = props.stripes.logger;
    this.log = this.logger.log.bind(this.logger);
    this.state = {
      searchForm: {}
    };
  }

  componentDidMount() {
    this.source = new StripesConnectedSource(this.props, this.logger);
  }

  componentDidUpdate() {
    this.source.update(this.props, 'smsDetailsRecords');
  }

  componentWillUnmount() {
    const { mutator, resources } = this.props;

    mutator.notifyLogQuery.replace('');
  }

  search = ({ requestPreferences, creds, ...formData }) => {
    const { mutator } = this.props;
    let query = '';
    if (formData) {
      if (formData.accountType) {
        query += ` and accountType == ${formData.accountType}`;
      }
      if (formData.messageType) {
        query += ` and messageType == ${formData.messageType}`;
      }
      if (formData.notifyMode) {
        query += ` and notifyMode == ${formData.notifyMode}`;
      }
      if (formData.name) {
        query += ` and name = ${formData.name}*`;
      }
      if (formData.userAccount) {
        query += ` and name = ${formData.userAccount}*`;
      }
      if (formData.sendDate) {
        query += ` and sendDate >= ${formData.sendDate} 00:00:00 `;
        query += ` and sendDate <= ${formData.sendDate} 23:59:59 `;
      }
      query = `${query.substr(4, query.length)}`;
    }

    mutator.notifyLogQuery.replace(query);
    if (this.source) {
      this.source.update(this.props, 'smsDetailsRecords');
      this.setState({
        searchForm: formData
      });
    }
  };

  moreData = () => {
    if (this.source) {
      this.source.fetchMore(10);
    }
  };

  exportExcel = () => {
    const params = this.state.searchForm;
    const p = params;
    const okapi = this.props.okapi;
    const path = okapi.url + '/party/notify_log/export_excel';
    const requestParams = ExprotExcel.objToParam(p);
    const fileName = '短信发送日志导出';
    const type = 'GET';
    ExprotExcel.exprot(
      path,
      requestParams,
      type,
      fileName,
      okapi.token,
      okapi.tenant
    );
  };

  render() {
    const { resources, dictionary } = this.props;
    if (this.source) {
      this.source.update(this.props, 'smsDetailsRecords');
    }

    const able = document.getElementsByClassName('mclScrollable---IM56u');
    if (able && able[0]) {
      able[0].style.width = '102%';
    }

    const totalCount = this.source ? this.source.totalCount() : 0;
    const dataList = get(resources, 'smsDetailsRecords.records', []);
    const formatter = {
      serialNumber: (
        <FormattedMessage id="ui-party.loans.columns.serialNumber" />
      ),
      activityName: (
        <FormattedMessage id="ui-party.loans.columns.party.partyName" />
      ),
      reserveChannel: (
        <FormattedMessage id="ui-party.loans.columns.reserve.channel" />
      ),
      accountType: <FormattedMessage id="ui-party.loans.columns.notify.log.account.type" />,
      userAccount: <FormattedMessage id="ui-party.loans.columns.readerAccount" />,
      name: <FormattedMessage id="ui-party.loans.columns.notify.log.name" />,
      phoneNumber: <FormattedMessage id="ui-party.loans.columns.notify.log.phone" />,
      messageType: <FormattedMessage id="ui-party.loans.columns.notify.log.message.type" />,
      sendStatus: <FormattedMessage id="ui-party.loans.columns.source.state" />,
      notifyMode: <FormattedMessage id="ui-party.loans.columns.notify.log.message.channel" />,
      message: <FormattedMessage id="ui-party.loans.columns.notify.log.message" />,
      sendDate: <FormattedMessage id="ui-party.loans.columns.notify.log.message.sendDate" />
    };
    return (
      <div>
        <SearchForm
          onSubmit={this.search}
          exportExcel={() => {
            this.exportExcel();
          }}
        />
        <MultiColumnList
          interactive={false}
          height={500}
          isEmptyMessage={<FormattedMessage id="ui-party.empty.list" />} // 空数据提示
          totalCount={totalCount}
          virtualize
          contentData={dataList}
          onNeedMoreData={this.moreData}
          columnMapping={formatter}
          columnWidths={{
            serialNumber: '5%',
            accountType: '10%',
            userAccount: '10%',
            name: '10%',
            phoneNumber: '10%',
            messageType: '10%',
            notifyMode: '10%',
            message: '15%',
            sendDate: '15%',
            activityName: '15%'
          }}
          visibleColumns={[
            'serialNumber',
            'activityName',

            'reserveChannel',
            'name',
            'message',
            'sendDate',
            'messageType',
            'notifyMode',
            'sendStatus',
            'accountType',

            'userAccount',

            'phoneNumber',

          ]}
          formatter={{
            reserveChannel: (item) => {
              if (item.reserveChannel) {
                if (item.reserveChannel === '1') {
                  return <span><FormattedMessage id={"ui-party.loans.columns.channel.wechat"}/></span>;
                } else if (item.reserveChannel === '2') {
                  return <span><FormattedMessage id={"ui-party.loans.columns.channel.back.kitchen"}/></span>;
                } else if (item.reserveChannel === '3') {
                  return <span><FormattedMessage id={"ui-party.loans.columns.channel.web"}/></span>;
                }
              }
              return '';
            },
            serialNumber: item => [<span>{item.rowIndex + 1}</span>],
            accountType: item => {
              let accessType = <FormattedMessage id={"ui-party.other.please.select.account.admin"}/>;
              if (item.accountType === 1) {
                accessType =  <FormattedMessage id={"ui-party.other.please.select.account.reader"}/>;
              }
              return <span>{accessType}</span>;
            },
            notifyMode: item => {
              if (item.notifyMode) {
                if (item.notifyMode === '1') {
                  return <span><FormattedMessage id={"ui-party.loans.columns.channel.wechat"}/></span>;
                } else if (item.notifyMode === '2') {
                  return <span><FormattedMessage id={"ui-party.messageTemplate.data.notice.textMessage"}/></span>;
                } else if (item.notifyMode === '3') {
                  return <span><FormattedMessage id={"ui-party.messageTemplate.data.notice.email"}/></span>;
                }
              }
              return '';
            },
            message: item => [
              <div
                title={item.message}
                style={{
                  whiteSpace: 'nowrap',
                  overflow: 'hidden',
                  textOverflow: 'ellipsis'
                }}
              >
                {item.message}
              </div>
            ],
            sendStatus: item => {
              let sendStatus = <FormattedMessage id={"ui-party.other.success"}/>;
              if (item.sendStatus != null && !item.sendStatus) {
                sendStatus =  <FormattedMessage id={"ui-party.other.failed"}/>;
              }
              return sendStatus;
            },
            messageType: item => {
              let messageType = '';
              if (item.messageType === 1) {
                messageType = <FormattedMessage id={"ui-party.other.sign.up.successfully"}/>;;
              } else if (item.messageType === 2) {
                messageType =<FormattedMessage id={"ui-party.other.attend.successfully"}/>;
              } else if (item.messageType === 3) {
                messageType = <FormattedMessage id={"ui-party.other.activity.approved"}/>;
              } else if (item.messageType === 4) {
                messageType = <FormattedMessage id={"ui-party.other.activity.unapproved"}/>;
              } else {
                messageType = <FormattedMessage id={"ui-party.other.emegency.notice"}/>;
              }

              return (
                <div
                  title={item.messageType}
                  style={{
                    whiteSpace: 'nowrap',
                    overflow: 'hidden',
                    textOverflow: 'ellipsis'
                  }}
                >
                  {messageType}
                </div>
              );
            },
            activityName: item => [
              <div
                title={item.partyName}
                style={{
                  whiteSpace: 'nowrap',
                  overflow: 'hidden',
                  textOverflow: 'ellipsis'
                }}
              >
                {item.partyName}
              </div>
            ]
          }}
        />
      </div>
    );
  }
}

export default stripesConnect(SmsDetailsStatistics);
